package com.card.client.dialog;

import java.util.ArrayList;

import com.card.client.entry.FinanceType;
import com.card.client.entry.OutputAccounts;
import com.card.client.entry.UserInfo;
import com.card.client.entry.Util;
import com.card.client.service.FinanceTypeConfigService;
import com.card.client.service.FinanceTypeConfigServiceAsync;
import com.card.client.service.OutputAccountsService;
import com.card.client.service.OutputAccountsServiceAsync;
import com.card.client.service.UserInfoManageService;
import com.card.client.service.UserInfoManageServiceAsync;
import com.card.client.view.OutputAccountsView;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.user.datepicker.client.DateBox.DefaultFormat;

public class EditOutputAccountsDialog extends DialogBox {

	private static EditOutputAccountsDialogUiBinder uiBinder = GWT
			.create(EditOutputAccountsDialogUiBinder.class);

	interface EditOutputAccountsDialogUiBinder extends UiBinder<Widget, EditOutputAccountsDialog> {
	}

	private final FinanceTypeConfigServiceAsync ftcs = GWT.create(FinanceTypeConfigService.class);
	
	private final OutputAccountsServiceAsync oas = GWT.create(OutputAccountsService.class);
	
	private final UserInfoManageServiceAsync uims = GWT.create(UserInfoManageService.class);
	
	private Long id;
	
	@UiField TextBox explain;
	
	@UiField TextBox outputAccounts;
	
	@UiField ListBox financeType;
	
	@UiField DateBox appendTime;
	
	@UiField Button submit;
	
	@UiField Button closeDialog;
	
	@UiField Label message;
	
	OutputAccountsView outputAccountsView;
	
	OutputAccounts oAccounts;
	
	UserInfo loginedUser;

	public EditOutputAccountsDialog(String title, String descript, OutputAccountsView outputAccountsView, OutputAccounts outputAccounts, int flag) {
		setWidget(uiBinder.createAndBindUi(this));
		setTitle(title);
		setText(descript);
		setGlassEnabled(true);
		setAnimationEnabled(true);
		setModal(true);
		message.setStyleName("descript");
		explain.setMaxLength(Util.INPUT_TEXT_MAX_LENGTH * 3);
		this.outputAccounts.setMaxLength(Util.INPUT_TEXT_MAX_LENGTH);
		center();
		this.outputAccountsView = outputAccountsView;
		DateTimeFormat dateTimeFormat = DateTimeFormat.getFormat("yyyy-MM-dd");
		DefaultFormat defaultFormat = new DefaultFormat(dateTimeFormat);
		appendTime.setFormat(defaultFormat);
		ftcs.getAllFinanceType(new AsyncCallback<FinanceType[]>() {
			public void onSuccess(FinanceType[] result) {
				ArrayList<FinanceType> list = new ArrayList<FinanceType>();
				for(int i=0;i<result.length;i++){
					FinanceType ft = result[i];
					if(ft.getTypeInOut() == Util.FINANCE_TYPE_AMOUNT_OUT){
						list.add(ft);
					}
				}
				if(list.size()<1){
					financeType.addItem("没有支出财务类型，不能添加账目", "0");
					submit.setEnabled(false);
				} else {
					financeType.addItem("", "0");
				}
				for(int i=0;i<list.size();i++){
					FinanceType ft = list.get(i);
					String id = Long.toString(ft.getId());
					financeType.addItem(ft.getFinanceType(), id);
				}
				if(null != oAccounts){
					int index = 0;
					String id = Long.toString(oAccounts.getFinanceTypeId());
					for(int i=0;i<financeType.getItemCount();i++){
						String value = financeType.getValue(i);
						if(value.equals(id)){
							index = i;
						}
					}
					financeType.setSelectedIndex(index);
				}
			}
			public void onFailure(Throwable caught) {}
		});
		submit.setText("添加");
		if(flag == Util.DIALOG_CONTROL_EDIT){
			submit.setText("修改");
			this.oAccounts = outputAccounts;
			setContent();
		}
		uims.getLoginedUser(new AsyncCallback<UserInfo>() {
			public void onSuccess(UserInfo result) {
				loginedUser = result;
			}
			public void onFailure(Throwable caught) {}
		});
		int w = this.outputAccounts.getOffsetWidth() + 1;
		financeType.setWidth(w + "px");
	}

	@UiHandler("submit")
	void onClickSubmit(ClickEvent e) {
		if(!isValid()){
			return;
		}
		OutputAccounts oa = new OutputAccounts();
		oa.setId(id);
		oa.setExplain(explain.getText());
		oa.setAccounts(Util.strToInt(outputAccounts.getText()));
		oa.setAppendTime(appendTime.getValue());
		int index = financeType.getSelectedIndex();
		String value = financeType.getValue(index);
		oa.setFinanceTypeId(Long.valueOf(value));
		if(null != id){
			oa.setUserId(oAccounts.getUserId());
			oas.updateOutputAccounts(oa, new AsyncCallback<Void>() {
				public void onSuccess(Void result) {
					hide();
					outputAccountsView.onLoad();
				}
				public void onFailure(Throwable caught) {}
			});
		} else {
			oa.setUserId(loginedUser.getId());
			oas.addOutputAccounts(oa, new AsyncCallback<Void>() {
				public void onSuccess(Void result) {
					hide();
					outputAccountsView.onLoad();
				}
				public void onFailure(Throwable caught) {}
			});
		}
	}

	@UiHandler("closeDialog")
	void onClickCloseDialog(ClickEvent e) {
		hide();
		outputAccountsView.onLoad();
	}
	
	public void setOutputAccounts(OutputAccounts outputAccounts){
		this.oAccounts = outputAccounts;
		setContent();
	}
	
	private void setContent(){
		if(oAccounts==null){
			return;
		}
		id = oAccounts.getId();
		int index = 0;
		for(int i=0;i<financeType.getItemCount();i++){
			String value = financeType.getItemText(i);
			if(value.equals(oAccounts.getFinanceTypeId())){
				index = i;
			}
		}
		explain.setText(oAccounts.getExplain());
		outputAccounts.setText(Long.toString(oAccounts.getAccounts()));
		financeType.setSelectedIndex(index);
		appendTime.setValue(oAccounts.getAppendTime());
	}
	
	private void setMessage(String msg){
		message.setText(msg);
	}
	
	private boolean isValid(){
		setMessage("");
		String check = Util.validInput(explain.getText());
		if(null != check){
			explain.setFocus(true);
			setMessage("支出说明" + check);
			return false;
		}
		check = Util.validInput(outputAccounts.getText());
		if(null != check){
			outputAccounts.setFocus(true);
			setMessage("支出金额" + check);
			return false;
		}
		check = Util.validAmount(outputAccounts.getText());
		if(null != check){
			outputAccounts.setFocus(true);
			setMessage(check);
			return false;
		}
		int index = financeType.getSelectedIndex();
		String value = financeType.getValue(index);
		if("0".equals(value)){
			financeType.setFocus(true);
			setMessage("没有选择支出类型");
			return false;
		}
		check = Util.validInput(appendTime.getTextBox().getText());
		if(null != check){
			appendTime.setFocus(true);
			setMessage("支出日期" + check);
			return false;
		}
		return true;
	}
}
